package jcataloger.data;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.List;

import jcataloger.beans.DiskImageInfo;

/**
 * This class is used to save all images into a file.
 * @author sekobey
 *
 */
public class DiskImage implements Serializable {
	private List<DiskImageInfo> images;
	private boolean isDirty;
	private static DiskImage diskImage;

	private DiskImage() {
		setDirty(false);
	}
	
	/**
	 * 
	 * @return an instance of this class.
	 */
	public static DiskImage getInstance() {
		if ( diskImage == null )
			return diskImage = new DiskImage();
		return diskImage;
	}
	
	/**
	 * writes the images to the given path.
	 * @param path the path to save images
	 */
	public void write(String path) {
		File f = new File(path);
		write(f);
	}
	
	/**
	 * writes the images to the given file.
	 * @param file file to save images
	 */
	public void write(File file) {
		try {
			ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
			oos.writeObject(images);
			oos.close();
			setDirty( false );
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * reads a file from the given path.
	 * @param path
	 */
	public void read(String path) {
		File f = new File(path);
		read(f);
	}

	/**
	 * reads a file from the given file.
	 * @param file
	 */
	public void read(File file) {
		try {
			ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
			List<DiskImageInfo> images = (List<DiskImageInfo>)ois.readObject();
			ois.close();
			setImages( images );
			setDirty( false );
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * returns the disk images in the catalog
	 * @return
	 */
	public List<DiskImageInfo> getImages() {
		return images;
	}

	/**
	 * sets the new images to be written.
	 * @param images
	 */
	public void setImages(List<DiskImageInfo> images) {
		this.images = images;
	}
	
	/**
	 * used for checking if a change in images has happened.
	 * @return true or false.
	 */
	public boolean isDirty() {
		return isDirty;
	}

	/**
	 * sets the images if there is change or not.
	 * @param isDirty
	 */
	public void setDirty(boolean isDirty) {
		this.isDirty = isDirty;
	}
}
